package fr.auzaiphe.commun;

import java.io.IOException;
import java.net.URL;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.DataLine.Info;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

/**
 * Lecture de sons basé sur SimpleAudioPlayer
 * Utilisation :
 *   -- Création de l'objet
 *   SoundPlayer monSon = new SoundPlayer("audio/events/my_event_song.wav");
 *   -- Lancement du son
 *   monSon.play();
 * @important Fonctionne avec le WAV
 * @author Anthony REY
 * @see http://www.jsresources.org/examples/SimpleAudioPlayer.html
 * @since 20/05/2012
 */
public class SoundPlayer
{
	private static final int EXTERNAL_BUFFER_SIZE = 128000;
	private URL soundFile;

	/**
	 * Constructeur du son à jouer
	 * @param pFileName Lien vers le son
	 */
	public SoundPlayer(String pFileName)
	{
		this.soundFile = this.getClass().getResource( pFileName );
	}

	/**
	 * Joue le son
	 */
	public void play()
	{
		SourceDataLine line;
		AudioInputStream audioInputStream;
		Info info;
		AudioFormat audioFormat;

		audioInputStream = null;
		try
		{
			audioInputStream = AudioSystem.getAudioInputStream(this.soundFile);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			//System.exit(1);
		}
		audioFormat = audioInputStream.getFormat();

		line = null;
		info = new DataLine.Info(SourceDataLine.class,
												 audioFormat);
		try
		{
			line = (SourceDataLine) AudioSystem.getLine(info);
			line.open(audioFormat);
		}
		catch (LineUnavailableException e)
		{
			e.printStackTrace();
			//System.exit(1);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			//System.exit(1);
		}

		line.start();
		int	nBytesRead = 0;
		byte[]	abData = new byte[EXTERNAL_BUFFER_SIZE];
		while (nBytesRead != -1)
		{
			try
			{
				nBytesRead = audioInputStream.read(abData, 0, abData.length);
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
			if (nBytesRead >= 0)
			{
				//int	nBytesWritten = line.write(abData, 0, nBytesRead);
				line.write(abData, 0, nBytesRead);
			}
		}
		line.drain();
		line.close();
	}
}